import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class Homework_TcpEchoClient {
    private Socket socket = null;
    public Homework_TcpEchoClient(String serverIp, int serverPort) throws IOException {
        //需要提供服务器的ip地址和端口号
        socket = new Socket(serverIp, serverPort);
    }
    public void start(){
        System.out.println("客户端启动！");
        try(InputStream inputStream = socket.getInputStream();
            OutputStream outputStream = socket.getOutputStream()){
            Scanner scanner = new Scanner(System.in);
            Scanner socketScanner = new Scanner(inputStream);
            PrintWriter writer = new PrintWriter(outputStream);
            while (true){
                //1.给服务器发送请求
                String request = scanner.next();
                writer.println(request);
                writer.flush();
                //2.等待服务器响应
                String response = socketScanner.next();
                //3.打印响应
                System.out.println(response);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Homework_TcpEchoClient client = new Homework_TcpEchoClient("127.0.0.1", 9999);
        client.start();
    }
}
